/*************************************************************************
 *                    free                     *
 *************************************************************************
 *************************************************************************
 * Filename	   : main.c
 * Description   : This is the main file ,it contains the main function entrance
 * Version	   : 1.0
 * History       :
 free 2013-4-15  Create
 *************************************************************************/
#include <stdio.h>
#include "package_length.h"
#include "table_pat.h"
#include "table_pmt.h"
#include "table_sdt.h"
#include "package_process.h"
#include "user_interface.h"

#define INPUT_FILE_NAME 		"../TS/mux.ts"
#define OUTPUT_FILE_NAME 		"../TS/hello.ts"

int main(void)
{
	FILE *pInputFile = NULL;
	int iPackageLength = 0;
	int iCopyFileResult = 0;
	long int liFirstPackageOffset = 0L;

	pInputFile = fopen(INPUT_FILE_NAME, "rb");
	if (pInputFile == NULL )
	{
		printf("open input file error!\n");
		return 0;
	}
	iPackageLength = GetPackageLength(pInputFile, &liFirstPackageOffset);
	if (iPackageLength != 0)
	{
		int iServiceId = 0;
		SECTION_PMT *pstTablePmt = NULL;
		SECTION_PAT *pstTablePat = GetTablePat(pInputFile, liFirstPackageOffset, iPackageLength);
		PMT_TABLELIST *pstPmtTableList = GetTableListPmt(pstTablePat, pInputFile, liFirstPackageOffset, iPackageLength);
		SECTION_SDT *pstTableSdt = GetTableSdt(pInputFile, liFirstPackageOffset, iPackageLength);

		if (GetParseTableResult(pstTablePat, pstPmtTableList, pstTableSdt) == 1)
		{
			while (1)
			{
				iServiceId = GetUserServiceId(pstTableSdt);
				if (iServiceId == -1)
				{
					break;
				}
				pstTablePmt = GetPmtByProgramNumber(pstPmtTableList, iServiceId);
				iCopyFileResult = CopyToFileByPmt(pInputFile, OUTPUT_FILE_NAME, iPackageLength, liFirstPackageOffset, pstTablePmt);
				ShowCopyFileResult(iCopyFileResult);
			}
		}
		FreeTableSdt(&pstTableSdt);
		FreeTableListPmt(&pstPmtTableList);
		FreeTablePat(&pstTablePat);
	}
	fclose(pInputFile);
	return 0;
}

